package com.jshoperxms.components.upload;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jshoperxms.Response;
import com.jshoperxms.components.upload.qiniu.ImgFileBean;
import com.jshoperxms.components.upload.qiniu.QiNiuConfig;
import com.jshoperxms.components.upload.qiniu.QiNiuUploadFiles;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.config.GlobalParam;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.RedisKey;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.redis.RedisBaseOperation;
import com.jshoperxms.redis.RedisBaseTDao;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by sdywcd on 16/9/25.
 * Des:
 */
@Controller
@RequestMapping("/mall/files")
public class FileUplaodController extends BaseTController {
    private Map<String,Object> responsedata=new HashMap<>();
    @Resource
    private RedisBaseTDao<String> redisBaseTDao;


    @RequestMapping(value="/ajaxFileUploadsImgs",method= RequestMethod.POST)
    public ResponseEntity ajaxFileUploadsImgs(@RequestParam("file")MultipartFile file, @RequestParam("filename") String filename){
        QiNiuUploadFiles qiniu=new QiNiuUploadFiles();
        String extName = StaticKey.EMPTY;
        String newFileFullname = StaticKey.EMPTY;// 包含后缀的文件名
        String newFileName = StaticKey.EMPTY;// 没有包含后缀的文件名
        String nowTimeStr = StaticKey.EMPTY;
        String realpath = FileTools.isExistdir();
        SimpleDateFormat sDateFormat;
        Random r = new Random();
        String savePath = request.getSession().getServletContext().getRealPath(
                File.separator);
        savePath = savePath + realpath;
        int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
        sDateFormat = new SimpleDateFormat(StaticKey.DF_YYYYMMDDHHMMSS);
        nowTimeStr = sDateFormat.format(new Date());
        if(filename.lastIndexOf(TagWords.DOT)>=0){
            extName=filename.substring(filename.lastIndexOf(TagWords.DOT));
        }
        // 包含后缀的文件全名
        newFileFullname = nowTimeStr + rannum + extName;
        // 不包含后缀的文件全名
        newFileName = nowTimeStr + rannum;
        PrintWriter writer = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            if(!file.isEmpty()){
                byte[] bytes=file.getBytes();
                BufferedOutputStream stream=new BufferedOutputStream(new FileOutputStream(new File(savePath + newFileFullname)));
                stream.write(bytes);
                stream.close();
            }
            ImgFileBean ifb = new ImgFileBean();
            ifb.setBasepath(BaseTools.getBasePath()+"/");
            String localFile = savePath + newFileFullname;// 已上传到本地的图片路径
            String cloudFileKey = realpath + newFileFullname;// 云上的文件名称
            String compressLocalFile = StaticKey.EMPTY;// 已上传到本地的压缩图片路径
            String compresscloudFileKey = StaticKey.EMPTY;// 云上的压缩文件名称
            String configstrs=this.redisBaseTDao.get(RedisKey.CONFIG,RedisKey.CONFIG);
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
                    .create();
            Map<String, String> configs = gson.fromJson(
                    configstrs,
                    new TypeToken<Map<String, String>>() {
                    }.getType());

            cloudFileKey = cloudFileKey.replace('\\', '/');

            // 检测是否启用云存储图片
            String issaveimgtocloud =configs.get(GlobalParam.ISSAVEIMGTOCLOUD);
            if(issaveimgtocloud!=null) {
                if (StringUtils.equals(issaveimgtocloud, StaticKey.ONE)) {
                    qiniu.uploads(localFile, cloudFileKey);
                    response.setStatus(HttpServletResponse.SC_OK);
                    ifb.setSucflag(true);
                    ifb.setCloudImg(true);
                    ifb.setBasepath(StaticKey.EMPTY);
                    ifb.setNormalfilepath(QiNiuConfig.QINIUIMGHOST
                            + cloudFileKey);
                } else if (StringUtils.equals(issaveimgtocloud, StaticKey.ZERO)) {
                    // 如果不启用云存储表示本地存储
                    ifb.setSucflag(true);
                    ifb.setBasepath(BaseTools.getBasePath());
                    ifb.setNormalfilepath(cloudFileKey);
                }
            }

            boolean isImg = ImgCutTools.checkIsImg(extName);
            if (isImg) {
                // 检测是否需要压缩图片
                String isimagecompression =configs.get(GlobalParam.ISIMAGECOMPRESSION);
                if(isimagecompression!=null) {
                    if (isimagecompression.equals(StaticKey.ONE)) {
                        // 只有当开启压缩时才执行压缩方法并保存缩略图
                        int width =Integer.parseInt(configs.get(GlobalParam.THUMBNAILWIDTH));
                        int height = Integer.parseInt(configs.get(GlobalParam.THUMBNAILHEIGHT));
                        compressLocalFile = ImgCutTools.compressImages(localFile,
                                savePath, width, height);
                        compresscloudFileKey = realpath + nowTimeStr + rannum  + TagWords.UNDERLINE
                                + String.valueOf(width) + TagWords.UNDERLINE
                                + String.valueOf(height) + extName;
                        compresscloudFileKey = compresscloudFileKey.replace('\\', '/');
                        if (compressLocalFile != null) {
                            if (StringUtils.equals(issaveimgtocloud, StaticKey.ONE)) {
                                // 调用七牛云存储，存储压缩后的图片
                                qiniu.uploads(compressLocalFile, compresscloudFileKey);
                                ifb.setSucflag(true);
                                ifb.setCloudImg(true);
                                ifb.setBasepath(StaticKey.EMPTY);
                                ifb.setCompressfilepath(QiNiuConfig.QINIUIMGHOST
                                        + compresscloudFileKey);
                            } else if (StringUtils.equals(issaveimgtocloud,
                                    StaticKey.ZERO)) {
                                ifb.setSucflag(true);
                                ifb.setBasepath(BaseTools.getBasePath());
                                ifb.setCompressfilepath(realpath
                                        + compresscloudFileKey);
                            }
                        }
                    }
                }

                // 检测是否本地保存原图，如果不保存原图意味着删除本地图片
                String issaveoriginalbitmap = configs.get(GlobalParam.ISSAVEORIGINALBITMAP);
                if(issaveoriginalbitmap!=null) {
                    if (StringUtils.equals(issaveoriginalbitmap, StaticKey.ZERO)) {
                        // 删除本地原图
                        File localoriginalFile = new File(localFile);
                        if (localoriginalFile != null) {
                            if (localoriginalFile.exists() && localoriginalFile.isFile() && !localoriginalFile.isHidden()) {
                                localoriginalFile.delete();
                            }
                        }
                        // 删除本地压缩图
                        File compressFile = new File(compressLocalFile);
                        if (compressFile != null) {
                            if (compressFile.exists() && compressFile.isFile()
                                    && !compressFile.isHidden()) {
                                compressFile.delete();
                            }
                        }
                    }
                }

            }
            responsedata.put(TagWords.IFB,ifb);
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {

        }

        return Response.success(responsedata);
    }

}

